<?php

namespace app\model\system;

use app\model\BaseModel;
use support\Log;
use think\model\concern\SoftDelete;

/**
 *
 */
class SysUser extends BaseModel
{

    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = "sys_user";

    protected $hidden = ['password', 'openid'];

    public function roles()
    {
        return $this->belongsToMany(SysRole::class, 'sys_user_role', 'role_id', 'user_id');
    }

    public function getRoleCodes(): array
    {
        $roleCodes = [];
        foreach ($this->roles as $role) {
            $roleCodes[] = $role->code;
        }
        return $roleCodes;
    }

    public function getRoleIds(): array
    {
        $roleIds = [];
        foreach ($this->roles as $role) {
            $roleIds[] = (int)$role->id;
        }
        return $roleIds;
    }

    public function getRoleMenuIds(): array
    {
        $menuIds = [];
        foreach ($this->roles as $role) {
            foreach ($role->menus as $menu) {
                $menuIds[] = $menu->id;
            }
        }
        return array_unique($menuIds);
    }

    public function getPerms(): array
    {
        $perms = [];
        foreach ($this->roles as $role) {
            foreach ($role->menus as $menu) {
                if ($menu->type == SysMenu::BUTTON) {
                    $perms[] = $menu->perm;
                }
            }
        }
        return array_unique($perms);
    }

    public function getTreeMenus(): array
    {
        $treeMenus = [];
        $menuIds = $this->getRoleMenuIds();
        $menus = SysMenu::where('parent_id', 0)->select();
        foreach ($menus as $menu) {
            if (in_array($menu->id, $menuIds) && in_array($menu->type, [SysMenu::MENU, SysMenu::CATLOG, SysMenu::LINK])) {
                $treeMenus[] = $menu->getRoutes($menuIds);
            }
        }
        return $treeMenus;
    }

    public function getFormArray(): array
    {
        return [
            'id' => $this->id,
            'username' => $this->username,
            'nickname' => $this->nickname,
            'gender' => $this->gender,
            'avatar' => $this->avatar,
            'mobile' => $this->mobile,
            'email' => $this->email,
            'status' => $this->status,
            'deptId' => $this->deptId,
            'openId' => $this->openId,
            'roleIds' => $this->getRoleIds(),
        ];
    }
    public function toArray(array $merges = []): array
    {
        $modelArray = $this->getFormArray() + [
            'roles' => $this->getRoleCodes(),
            'perms' => $this->getPerms(),
            'deptName' => $this->deptName,
            'createTime' => $this->createTime
        ];

        return $this->merge($modelArray, $merges);
    }
}
